﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using KSUNO_EMS.Models;

namespace KSUNO_EMS.Controllers
{
    public class StudyMaterialsManagementController : EmsController
    {
        //
        // GET: /StudyMaterialsManagement/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Delete(int id)
        {
            Database.Documents.Remove(Database.Documents.Single(d => d.Id == id));
            Database.SaveChanges();
            return new ProperJsonResult() { Data = new AjaxResult(true) };
        }

        public ActionResult ListMaterials()
        {
            return new ProperJsonResult() { Data = new AjaxResult(true, Database.Documents.ToList().Select(Mapper.Map<Document, DocumentDTO>)) };
        }

        [HttpPost]
        public ActionResult Upload(string name)
        {
            var request = Request;
            byte[] data;
            var info = Uploader.GetFile(Request, out data);
            var document = new Document() { Data = data, Name = name, FileExtension = info.fileExtension };
            Database.Documents.Add(document);
            Database.SaveChanges();

            return new ProperJsonResult() { Data = new AjaxResult(true, Mapper.Map<DocumentDTO>(document)) };
        }

        public FileResult View(int id)
        {
            var document = Database.Documents.Single(d => d.Id == id);
            return new FileContentResult(document.Data, "application/" + document.FileExtension.Substring(1));
        }
    }
}

